package cn.jinjimi.app;

import android.annotation.TargetApi;
import android.app.Application;
import android.os.Build;
import android.os.StrictMode;
import android.webkit.WebView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.mob.MobSDK;
import com.qiyukf.unicorn.api.StatusBarNotificationConfig;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.YSFOptions;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.EventBus;

import cn.jinjimi.app.bean.SharePrefKeys;
import cn.jinjimi.app.common.FrescoImageLoader;
import cn.jinjimi.app.main.widget.FrescoImageView.ImagePipelineConfigFactory;
import cn.jinjimi.app.managers.ConfigManager;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.util.AppUtils;
import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.domain.Dispatcher;
import cn.jinjimi.domain.ServiceManager;
import cn.jinjimi.domain.data.Config;
import cn.jinjimi.framework.analy.AnalyManager;

/**
 *
 * @author zhenhua
 * @date 17/1/14
 */

public class JJMApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        setupBaseModule();

        AccountManager.init(this);

        DatabaseManager.init(this);

        setupBugly(this);

        setupEventBus();

        setupStatistic(this);

        setupConfig(this);

        setupFresco(this);

        setupShare(this);

        setupUpdateManager(this);

        DatabaseManager.getInstance();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && BuildConfig.DEBUG) {
            //开启WebView的debug模式
            WebView.setWebContentsDebuggingEnabled(true);
        }

        ConfigManager.getInstance().hasMainActivityStarted(false);

        LogUtil.enable(BuildConfig.DEBUG);

        initQiyu();

        //detect things maybe doing by accident
        if (BuildConfig.DEBUG) {
            initSADetector();
        }
    }

    private void initQiyu() {
        YSFOptions options = new YSFOptions();
        options.statusBarNotificationConfig = new StatusBarNotificationConfig();
        Unicorn.init(this, "39d8f31746e0ce89bd2974c7d254fa1a", options, new FrescoImageLoader(this));
    }

    private void initSADetector() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
            .detectDiskReads()
            .detectDiskWrites()
            .detectNetwork()
            .penaltyLog()
            .build());

        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
            .detectLeakedSqlLiteObjects()
            .detectLeakedClosableObjects()
            .penaltyLog()
            .penaltyDeath()
            .build());
    }

    private void setupBaseModule() {
        PreferenceManager.init(this);
        AndroidUtils.init(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(Application.ActivityLifecycleCallbacks callbacks) {
        this.registerActivityLifecycleCallbacks(callbacks);
    }

    private void setupEventBus() {
        try {
            EventBus.builder()
                    .logNoSubscriberMessages(BuildConfig.DEBUG)
                    .logSubscriberExceptions(BuildConfig.DEBUG)
                    .sendNoSubscriberEvent(BuildConfig.DEBUG)
                    .sendSubscriberExceptionEvent(BuildConfig.DEBUG)
                    .throwSubscriberException(BuildConfig.DEBUG)
                    .installDefaultEventBus();
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 初始化统计模块
     *
     * @param application
     */
    private void setupStatistic(Application application) {
        AnalyManager.getInstance().initAnaly(application);
    }


    /**
     * 注册公共模块
     */
    private void setupConfig(Application application) {
        Config.register(application);
    }

    /**
     * 初始化Fresco图片加载器
     */
    private void setupFresco(Application application) {
        Fresco.initialize(application, ImagePipelineConfigFactory.getImagePipelineConfig(application));
    }

    /**
     * 初始化分享
     *
     * @param application
     */
    private void setupShare(Application application) {
        MobSDK.init(application);
    }

    /**
     * 初始化Bugly
     *
     * @param application
     */
    private void setupBugly(Application application) {
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(application);
        strategy.setAppChannel(AppUtils.getChannel());

        Beta.autoCheckUpgrade = true;
        Bugly.setIsDevelopmentDevice(application, BuildConfig.BUGLY_ENABLE_DEBUG);
        Bugly.init(application, BuildConfig.BUGLY_APPID_VALUE, BuildConfig.BUGLY_ENABLE_DEBUG, strategy);
    }

    /**
     * 初始化下载模块
     *
     * @param application
     */
    private void setupUpdateManager(Application application) {

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        onExit();
    }

    public void onExit() {
        PreferenceManager.setData(SharePrefKeys.PREF_APP_HAVE_IN, false);
        ServiceManager.getService(Dispatcher.class).onDestroy();
        DatabaseManager.getInstance().onTerminal();
    }

}
